import { defineEventHandler, readBody } from 'h3';
import { generateDrivers } from './data'

// 司机数据模拟
const drivers = generateDrivers();


// 检查联系电话是否已存在
export const checkPhoneExistsHandler = defineEventHandler(async (event) => {
  try {
    const body = await readBody(event);
    const { phoneNumber, excludeId } = body;

    const existingDriver = drivers.find(
      (driver) =>
        driver.phoneNumber === phoneNumber &&
        (excludeId ? driver.driverId !== excludeId : true),
    );

    return {
      code: 200,
      message: 'success',
      data: !!existingDriver,
    };
  } catch (error) {
    console.error('检查联系电话失败:', error);
    return {
      code: 500,
      message: '检查联系电话失败',
      data: false,
    };
  }
});

// 创建司机
export const createDriverHandler = defineEventHandler(async (event) => {
  try {
    const body = await readBody(event);
    const {
      fullName,
      phoneNumber,
      licenseLevel,
      emergencyContact,
      firstLicenseDate,
    } = body;

    // 检查联系电话是否已存在
    const existingDriver = drivers.find(
      (driver) => driver.phoneNumber === phoneNumber,
    );
    if (existingDriver) {
      return {
        code: 400,
        message: '该联系电话已存在，请更换',
        data: null,
      };
    }

    const newDriver = {
      driverId: Math.max(...drivers.map((d) => d.driverId)) + 1,
      fullName,
      phoneNumber,
      passwordHash: '$2b$10$hashedpassword', // 默认密码
      licenseLevel: licenseLevel || '',
      status: '在职',
      emergencyContact: emergencyContact || '',
      firstLicenseDate: firstLicenseDate || '',
      createTime: new Date().toISOString().split('T')[0],
      updateTime: new Date().toISOString().split('T')[0],
    };

    drivers.unshift(newDriver); // 添加到数组开头

    return {
      code: 200,
      message: '创建司机成功',
      data: newDriver,
    };
  } catch (error) {
    console.error('创建司机失败:', error);
    return {
      code: 500,
      message: '创建司机失败',
      data: null,
    };
  }
});

// 更新司机
export const updateDriverHandler = defineEventHandler(async (event) => {
  try {
    const driverId = Number.parseInt(event.context.params?.id as string);
    const body = await readBody(event);
    const {
      fullName,
      phoneNumber,
      licenseLevel,
      emergencyContact,
      firstLicenseDate,
    } = body;

    const driverIndex = drivers.findIndex(
      (driver) => driver.driverId === driverId,
    );
    if (driverIndex === -1) {
      return {
        code: 404,
        message: '司机不存在',
        data: null,
      };
    }

    // 检查联系电话是否已存在（排除当前司机）
    const existingDriver = drivers.find(
      (driver) =>
        driver.phoneNumber === phoneNumber && driver.driverId !== driverId,
    );
    if (existingDriver) {
      return {
        code: 400,
        message: '该联系电话已存在，请更换',
        data: null,
      };
    }

    const updatedDriver = {
      ...drivers[driverIndex],
      fullName,
      phoneNumber,
      licenseLevel: licenseLevel || '',
      emergencyContact: emergencyContact || '',
      firstLicenseDate: firstLicenseDate || '',
      updateTime: new Date().toISOString().split('T')[0],
    };

    drivers[driverIndex] = updatedDriver;

    return {
      code: 200,
      message: '更新司机成功',
      data: updatedDriver,
    };
  } catch (error) {
    console.error('更新司机失败:', error);
    return {
      code: 500,
      message: '更新司机失败',
      data: null,
    };
  }
});

// 分配车辆
export const assignVehiclesHandler = defineEventHandler(async (event) => {
  try {
    const driverId = Number.parseInt(event.context.params?.id as string);
    const body = await readBody(event);
    const { vehicleIds } = body;

    // 这里应该更新车辆表，将车辆分配给司机
    // 由于车辆API还未实现，这里先返回成功
    return {
      code: 200,
      message: '分配车辆成功',
      data: { driverId, vehicleIds },
    };
  } catch (error) {
    console.error('分配车辆失败:', error);
    return {
      code: 500,
      message: '分配车辆失败',
      data: null,
    };
  }
});
